var PrintPurchaseOrderTemplate = function () {
  var template = /*html*/ `
    <div class="print-warehouse-template" style="padding:20px;padding-top:0;height:calc(100% - 20px)" v-loading.fullscreen.lock="loading">
      <div style="margin-bottom:10px">
        <el-button type="primary" @click="print">打印</el-button>
        <template v-for="(searchBtn,index) in searchBtns">
          <span :key="'search-label_'+index">{{searchBtn.label}}</span>
          <el-select filterable class="template-item" v-if="searchBtn.type==='select'" v-model="searchBtn.value" :key="'search-btn_'+index" 
            style="width:220px;" @change="searchChange(searchBtn)">
            <el-option v-for="(option,optionIndex) in searchBtn.options" :key="'option_'+optionIndex" :value="option"></el-option>
          </el-select>
        </template>
      </div>

      <div style="height:calc(100% - 50px);overflow:auto;" v-if="printTemplData!==null&&printTemplate!==null">
        <sys-print-template-order ref="printTemplateOrder" :print-data="printTemplData" :print-template="printTemplate" :read-only="readOnly">
        </sys-print-template-order>
      </div>
    </div>
  `;

  return {
    props: {
      orderType: {
        type: [Number, String],
        default: ''
      }
    },

    mixins: [printOrderTemplateMixin('purchaseOrder')],

    data: function () {
      return {
        loading: false,
        purchaseNo: '',
        exist: false
      };
    },

    methods: {
      formatTemplate:function(printTemplate){
        var formatTemplate = printTemplate.formatTemplate;
        if (formatTemplate !== undefined) {
          printTemplate = this[formatTemplate](printTemplate);
        }
        return printTemplate;
      },

      removeOrderField:function(printTemplate){
        var orderType = this.orderType;
        if (orderType === 1) {
          return printTemplate;
        }

        var tableOptions = _.filter(printTemplate.options, {
          type:'table'
        });
        var hiddenFieldList = ['companyOrderId'];
        for (var i = 0; i < tableOptions.length; i++) {
          var tableOption = tableOptions[i];
          var tableConfig = tableOption.config;
          var tableBody = tableConfig.tableBody;
          var removeIndexs = [];
          for (var j = 0; j < tableBody.length; j++) {
            var body = tableBody[j];
            var checkHiddenField = body.checkHiddenField;
            if (checkHiddenField === undefined) {
              continue;
            }

            if (hiddenFieldList.indexOf(checkHiddenField) !== -1) {
              removeIndexs.push(j);
            }
          }

          SysUtil.arrayRemoveByIndexList(tableConfig.colWidths,removeIndexs);

          var tableHeader = tableConfig.tableHeader;
          for (var j = 0; j < tableHeader.length; j++) {
            var header = tableHeader[j];
            SysUtil.arrayRemoveByIndexList(header,removeIndexs);
          }
          SysUtil.arrayRemoveByIndexList(tableConfig.tableBody,removeIndexs);
          var tableStat = tableConfig.tableStat;
          if (tableStat !== undefined) {
            SysUtil.arrayRemoveByIndexList(tableStat,removeIndexs);
          }
        }

        return printTemplate;
      },

      print: function () {
        var exist = this.exist,
          purchaseNo = this.purchaseNo;
        if (exist || purchaseNo === '') {
          this.toPrint();
          return;
        }

        var searchData = this.searchData;
        var ids = _.map(searchData, 'printOrderId');
        this.loading = true;
        var self = this;
        ajaxRequest('order/updateBatchPurchaseOrderDetail', {
          ids: ids.join(','),
          type: this.orderType,
          ptId: purchaseNo,
          isPrint: 1
        }).then(function () {
          self.exist = true;
          self.toPrint();
          self.$emit('order-change', false);
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      setPrintData: function () {
        var searchBtns = this.searchBtns;
        var searchBtn = _.find(searchBtns, {
          field: 'providerName'
        });
        if (searchBtn !== undefined) {
          var searchData = this.searchData;
          var ids = _.map(searchData, 'printOrderId');
          var providerName = searchBtn.value;
          var self = this;
          this.loading = true;
          ajaxRequest('purchaseOrder/getPurchaseNoByProviderNameAndPurchaseDetailIds', {
            providerName: providerName,
            ids: ids.join(',')
          }).then(function (res) {
            var purchaseNo = res.purchaseNo;
            self.purchaseNo = purchaseNo;
            self.exist = res.exist;
            self.toSettingPrintTemplData({
              purchaseNo: purchaseNo,
              providerName: providerName
            });
            self.loading = false;
          }).catch(function () {
            self.loading = false;
          });
          return;
        }
        this.toSettingPrintTemplData({
          purchaseNo: '',
          providerName: ''
        });
      },

      toSettingPrintTemplData: function (option) {
        var searchData = _.clone(this.searchData);
        var purchasePeopleList = [];
        var approvalUserList = [];
        for (var i = 0; i < searchData.length; i++) {
          var data = searchData[i];
          var purchasePeople = data.purchasePeople;
          if (!SysUtil.isEmpty(purchasePeople)) {
            purchasePeopleList.push(purchasePeople);
          }

          var approvalUser = data.approvalUser;
          if (!SysUtil.isEmpty(approvalUser)) {
            approvalUserList.push(approvalUser);
          }
        }

        purchasePeopleList = _.uniq(purchasePeopleList);
        approvalUserList = _.uniq(approvalUserList);

        var providerName = option.providerName;
        var customer = _.find(searchData, {
          providerName: providerName
        });
        if (customer !== undefined) {
          customer = _.cloneDeep(customer.curstomer);
          customer.paymentWay = i18n.getMsg(`customer.paymentWayType.${customer.paymentWay}`);
        } else {
          customer = {};
        }

        var tableHead = {
          purchaseNo: option.purchaseNo,
          providerName: providerName,
          customer: customer,
          purchasePeopleList: purchasePeopleList,
          approvalUserList: approvalUserList,
          orderType:this.orderType
        };

        var maxLaterPhaseList = _.map(searchData, 'maxLaterPhase');
        var maxLaterPhase = _.max(maxLaterPhaseList);
        if (maxLaterPhase !== undefined) {
          tableHead.deliveryTime = maxLaterPhase;
          tableHead.deliveryEdit = false;
        } else {
          var proCycleList = _.map(searchData, 'procurementCycles');
          var proCycle = _.max(proCycleList);
          if (proCycle !== undefined) {
            tableHead.deliveryTime = moment().startOf('day').add(proCycle, 'day').valueOf();
          } else {
            tableHead.deliveryTime = null;
          }
          tableHead.deliveryEdit = true;
        }

        var purchaseTime;
        if (searchData.length === 0) {
          purchaseTime = moment().valueOf();
        } else {
          var purchaseData = _.maxBy(searchData, function (obj) {
            var purchaseTime = obj.purchaseTime;
            if (purchaseTime === '') {
              return -Infinity;
            }
            return moment(purchaseTime).valueOf();
          });
          purchaseTime = purchaseData.purchaseTime;
          if (purchaseTime === '') {
            purchaseTime = moment().valueOf();
          } else {
            purchaseTime = moment(purchaseTime).valueOf();
          }
        }
        tableHead.purchaseTime = purchaseTime;

        var data = {
          orderData: searchData,
          tableHead: tableHead
        };

        var self = this;
        SysUtil.getUser().then(function (user) {
          data.user = user;
          self.printTemplData = data;
        });
      }
    },

    template: template
  };
}();